<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-form label-width="80px">
        <el-form-item label="SPU名称">
          <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select placeholder="请选择" v-model="(spuInfo.tmId as number)">
            <el-option
              :label="item.tmName"
              :value="item.id"
              v-for="item in allTrademarkList"
              :key="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
          <el-input
            placeholder="SPU描述"
            type="textarea"
            v-model="spuInfo.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
          <el-upload
            v-model:file-list="fileList"
            :action="`${baseUrl}/admin/product/upload`"
            list-type="picture-card"
          >
            <el-icon><ele-Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="销售属性">
          <el-select
            :placeholder="`您还有${allSalesAttrList.length}个属性未选择`"
            v-model="SeleteSalesAttrInfo"
          >
            <el-option
              :label="item.name"
              :value="`${item.id}:${item.name}`"
              v-for="item in NoSelete"
              :key="item.id"
            >
            </el-option>
          </el-select>
          <el-button
            type="primary"
            size="default"
            @click="addSalesAttrValue"
            icon="ele-Plus"
            :disabled="!SeleteSalesAttrInfo"
            >添加属性值</el-button
          >
        </el-form-item>
        <el-table
          border
          stripe
          :style="{ margin: '20px 0' }"
          :data="salesAttrValueList"
        >
          <el-table-column type="index" width="80" label="序号" />
          <el-table-column label="属性名" prop="saleAttrName">
          </el-table-column>
          <el-table-column label="属性值名称列表">
            <template v-slot="{ row }">
              <div>
                <!-- 展示销售属性值 -->
                <el-tag
                  :style="{ marginLeft: '10px' }"
                  :type="`${index % 2 === 0 ? 'danger' : ''}`"
                  size="small"
                  closable
                  @close="closeTag(row.spuSaleAttrValueList, index)"
                  v-for="(item, index) in row.spuSaleAttrValueList"
                  :key="item.saleAttrValueName"
                  >{{ item.saleAttrValueName }}</el-tag
                >
                <!-- 销售属性值输入框 -->
                <el-input
                  v-if="row.isEdit"
                  placeholder="请输入销售属性值"
                  size="small"
                  clearable
                  @blur="toLook(row)"
                  ref="SalesAttrIptRef"
                  v-model="salesAttrIptValue"
                ></el-input>
                <!-- 点击添加销售属性值按钮 -->
                <el-button
                  v-else
                  type="primary"
                  size="small"
                  @click="toEdit(row)"
                  icon="ele-Plus"
                  >添加属性值</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="248"> </el-table-column>
        </el-table>

        <div>
          <el-button type="primary" size="default" @click="saveSpu"
            >保存</el-button
          >
          <el-button size="default" @click="cancel">取消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage, type UploadUserFile } from "element-plus";
import { cloneDeep } from "lodash";

export default defineComponent({
  name: "SpuInfo",
});
</script>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from "vue";
import {
  reqGetAllTrademarkList,
  type AllTrademarkListType,
} from "@/api/product";
import {
  reqAddSpuInfo,
  reqGetAllSalesAttrList,
  reqGetImageListBySpuId,
  reqGetSalesAttrListBySpuId,
  reqUpdataSpuInfo,
  type addSalesAttrListType,
  type PagingItemType,
  type salesAttrListType,
  type salseAttrItemType,
  type salseAttrValueListType,
} from "@/api/spu";

// 获取自定义事件
const emit = defineEmits<{
  (event: "cutSpuComponent", showIndex: number): void;
}>();
// 获取props
const props = defineProps<{
  spuInfo: PagingItemType;
}>();
// 照片墙数据
const fileList = ref<UploadUserFile[]>([]);
// 当前开发环境api
const baseUrl = import.meta.env.VITE_API_URL;

// 保存所有品牌列表
const allTrademarkList = ref<AllTrademarkListType>([]);

// 保存所有的销售属性列表
const allSalesAttrList = ref<salesAttrListType>([]);

// 用于新增时的数据收集
const spuInfo = ref<PagingItemType>(cloneDeep(props.spuInfo));

// 收集选择销售属性信息
const SeleteSalesAttrInfo = ref(``);

// 用于销售属性值列表
const salesAttrValueList = ref<addSalesAttrListType>([]);

// 添加属性值输入框ref
const SalesAttrIptRef = ref();

// 保存添加属性值输入框值
const salesAttrIptValue = ref("");

// 通过spuId 获取数据
// 获取销售属性列表
const getSalesAttrList = async () => {
  const result = await reqGetSalesAttrListBySpuId(spuInfo.value.id as number);
  // console.log(result);
  // 数据回填

  salesAttrValueList.value = result;
};
// 获取图片列表
const getImageList = async () => {
  const result = await reqGetImageListBySpuId(spuInfo.value.id as number);
  // console.log(result);
  // 数据回填
  result.forEach((item) => {
    const imageObj = {
      name: "",
      url: "",
    };
    imageObj.name = item.imgName;
    imageObj.url = item.imgUrl;
    fileList.value.push(imageObj);
  });
};

// 请求所有品牌数据
const getAllTrademarkList = async () => {
  const result = await reqGetAllTrademarkList();
  // 保存数据
  allTrademarkList.value = result;
};
// 请求所有销售属性
const getAllSalesAttrList = async () => {
  const result = await reqGetAllSalesAttrList();
  // 保存数据
  allSalesAttrList.value = result;
};

// 初始化请求数据
onMounted(() => {
  getAllTrademarkList();
  getAllSalesAttrList();
  // 当有spuid 时候才发送请求
  if (spuInfo.value.id) {
    getSalesAttrList();
    getImageList();
  }
});

// 点击添加属性值事件
const addSalesAttrValue = () => {
  // 获取属性信息
  const [baseSaleAttrId, saleAttrName] = SeleteSalesAttrInfo.value.split(":");
  // 给属性值列表添加数据
  salesAttrValueList.value.push({
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
    isEdit: false,
  });
  // 收集完成清空列表数据
  SeleteSalesAttrInfo.value = "";
};
// 计算出未选中的销售属性列表用于选择
const NoSelete = computed(() => {
  salesAttrValueList.value.forEach((item) => {
    const seleteIndex = allSalesAttrList.value.findIndex((it) => {
      return it.name === item.saleAttrName;
    });

    if (seleteIndex !== -1) allSalesAttrList.value.splice(seleteIndex, 1);
  });
  return allSalesAttrList.value;
});
// 点击添加属性值按钮
const toEdit = (row: salseAttrItemType) => {
  // 进入编辑模式
  row.isEdit = true;
  // 让输入框获取焦点
  nextTick(() => {
    SalesAttrIptRef.value.focus();
  });
  // 清空输入框数据
  salesAttrIptValue.value = "";
};
// 输入框失去焦点事件
const toLook = (row: salseAttrItemType) => {
  // 进入查看模式
  row.isEdit = false;
  // 非空验证
  if (!salesAttrIptValue.value) return ElMessage.error("销售属性值不能为空!");

  // 重复销售属性值验证
  const isReUse = row.spuSaleAttrValueList.some(
    (item) => item.saleAttrValueName === salesAttrIptValue.value
  );
  if (isReUse) return ElMessage.error("销售属性值不能相同！");
  // 添加属性值数据
  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrName: row.saleAttrName,
    saleAttrValueName: salesAttrIptValue.value,
  });
};

// 保存spu数据
const saveSpu = async () => {
  // 整理参数
  // 初始化数据
  spuInfo.value.spuImageList = [];
  spuInfo.value.spuSaleAttrList = [];
  // 图片
  fileList.value.forEach((item) => {
    // 将图片需要的参数取出
    const imageObj = {
      imgName: "",
      imgUrl: "",
    };
    imageObj.imgName = item.name;
    imageObj.imgUrl = (item.response as any).data;
    // 将收集的数据放到spuInfo中
    spuInfo.value.spuImageList?.push(imageObj);
  });
  // 销售属性值列表
  salesAttrValueList.value.forEach((item) => {
    spuInfo.value.spuSaleAttrList?.push(item);
  });

  console.log(spuInfo.value);

  if (spuInfo.value.id) {
    // 发送修改请求
    await reqUpdataSpuInfo(spuInfo.value);
  } else {
    // 发送新增请求
    await reqAddSpuInfo(spuInfo.value);
  }

  // 提示成功
  ElMessage.success("保存成功！");
  // 回到spuList
  emit("cutSpuComponent", 1);
};
// 点击属性值关闭按钮
const closeTag = (list: salseAttrValueListType, index: number) => {
  // console.log(index);
  list.splice(index, 1);
};
// 点击取消按钮 回到spuList
const cancel = () => {
  emit("cutSpuComponent", 1);
};
</script>

<style scoped lang="scss"></style>
